//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package events_subscribe

import (
	"fmt"

	"atomgit.com/openlinksaas/proto-gen-go.git/events/events_atomgit"
	"atomgit.com/openlinksaas/proto-gen-go.git/events_api"
)

func processAtomGitEvent(event *events_api.Event, cfgItemList []*CfgItem) (bool, error) {
	var err error
	var msg string
	{
		issueEvent := &events_atomgit.IssueEvent{}
		if event.EventData.MessageIs(issueEvent) {
			err = event.EventData.UnmarshalTo(issueEvent)
			if err != nil {
				return false, err
			}
			opt := "创建"
			if issueEvent.Action == "close" {
				opt = "关闭"
			} else if issueEvent.Action == "reopen" {
				opt = "重新打开"
			} else if issueEvent.Action == "deleted" {
				opt = "删除"
			}
			msg = fmt.Sprintf("%s 在项目 %s 源用户 %s %s工单 %s %s。", event.UserDisplayName, event.ProjectName,
				issueEvent.Sender.Login, opt, issueEvent.Issue.Title, issueEvent.Issue.Url)
			for _, cfgItem := range cfgItemList {
				if cfgItem.eventCfg.AtomgitEvCfg.Issue {
					sendChatMsg(msg, cfgItem.subItem)
				}
			}
			return true, nil
		}
	}

	{
		pushEvent := &events_atomgit.PushEvent{}
		if event.EventData.MessageIs(pushEvent) {
			err = event.EventData.UnmarshalTo(pushEvent)
			if err != nil {
				return false, err
			}
			lastCommit := ""
			if len(pushEvent.Commits) > 0 {
				lastCommit = pushEvent.Commits[len(pushEvent.Commits)-1].Message
			}
			msg = fmt.Sprintf("%s 在项目 %s 源用户 %s 推送 %s(%s),包含%d次提交,最后提交内容 %s。ref %s", event.UserDisplayName, event.ProjectName,
				pushEvent.Sender.Login, pushEvent.Repository.Name, pushEvent.Repository.Homepage, len(pushEvent.Commits), lastCommit, pushEvent.Ref)
			for _, cfgItem := range cfgItemList {
				if cfgItem.eventCfg.AtomgitEvCfg.Push {
					sendChatMsg(msg, cfgItem.subItem)
				}
			}
			return true, nil
		}
	}

	return false, nil
}
